import router from "../src/router";
import NProgress from "nprogress";
// import pinia
import useStorePinia from '@/store'
import "nprogress/nprogress.css";

NProgress.configure({
	ease: "ease",
	speed: 500,
});
const whiteList = ['/login', '/404'];
router.beforeEach(async (to, from, next) => {
	NProgress.start();
	// 获取pinia user信息
	const { user } = useStorePinia();
	const token = user.token;
	// 判断有token并且还有回去登录页面,直接回到首页
	if (token && to.path === '/login') {
		next('/');
	} else if (!token && !whiteList.includes(to.path)) {
		next('/login');
	} else {
		// 有token并且没有用户信息
		if (token && !user.UserInfo.id) {
			// 权限校验
			try {
				// 调用user方法
				await user.getUserInfo();
				// 动态添加路由
				user.addRoutes.forEach((item) => {
					router.addRoute(item);
				});
				next({
					...to,
					replace: true,
				});
			} catch (err) {
				user.Logout();
				next(`/login?returnUrl=${to.path}`);
			}
		} else {
			next();
		}
	}
});

router.afterEach((transition) => {
	NProgress.done();
});

